package com.inei.cie;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.inei.cie.capituloi.CapituloI_Activity;
import com.inei.cie.caratula.Caratula_AB_Activity;
import com.inei.cie.dao.PrincipalDao;
import com.inei.cie.entidades.PCar;
import com.inei.cie.utilitarios.ListadoLocalesAdapter;
import com.inei.cie.utilitarios.Variables;

public class Carga_Trabajo_Activity extends Activity {

	public List<PCar> lPCar;
	public List<PCar> lTemp;
	public EditText etBuscar;
	public ListView lvLocales;
	public PrincipalDao principal;
	public Variables var;
	public ProgressDialog progreso;

	public Dialog dialogo;

	public Dialog dialogoE;

	public EditText etClave;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.carga_trabajo);
		IniciarComponentes();
	}

	public void IniciarComponentes() {
		var = new Variables();

		etBuscar = (EditText) findViewById(R.id.etBuscar);
		lvLocales = (ListView) findViewById(R.id.lvLocales);
		lvLocales.setScrollContainer(false);
		principal = new PrincipalDao(this);

		lPCar = principal.ListadoLocales();
		lTemp = lPCar;
		if (lPCar != null) {
			ListadoLocalesAdapter adaptador = new ListadoLocalesAdapter(
					getApplicationContext(), lTemp);
			lvLocales.setAdapter(adaptador);
			etBuscar.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					FiltrarLista(s.toString());
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {
				}
			});
		}

		lvLocales.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adap, View v, int pos,
					long arg3) {

				CrearMenu(lTemp.get(pos));
			}
		});
	}

	public void FiltrarLista(String s) {
		lTemp = new ArrayList<PCar>();
		for (PCar pcar : lPCar) {
			if (pcar.getId_local().contains(s)) {
				lTemp.add(pcar);
			}
		}
		ListadoLocalesAdapter adaptador = new ListadoLocalesAdapter(
				getApplicationContext(), lTemp);
		lvLocales.setAdapter(adaptador);
	}

	public void CrearMenu(PCar pcar) {
		CharSequence[] items = new CharSequence[3];

		/*items[0] = "Cedula Censal";
		items[1] = "Exportar Data";
		items[2] = "Enviar Datos";
		items[3] = "Para Zonas Rurales";*/
		items[0] = "Cedula Censal";
		items[1] = "Exportar Data";
		items[2] = "Para Zonas Rurales";
		final String id_local = pcar.getId_local();
		final int Nro_Pred = pcar.getPC_F_1();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Local Nro " + id_local).setItems(items,
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0) {
							Intent irCaratula = new Intent(
									getApplicationContext(),
									Caratula_AB_Activity.class);
							Bundle b = getIntent().getExtras();
							// Bundle b = new Bundle();
							b.putInt("rural", 0);
							b.putString(var.ID_LOCAL, id_local);
							// b.putInt(var.NRO_PRED, 2);
							b.putInt(var.NRO_PRED, Nro_Pred);
							irCaratula.putExtras(b);
							startActivity(irCaratula);
							dialog.cancel();
							finish();
						} else if (which == 2) {
							int rural = 1;
							Intent irEnvio = new Intent(
									getApplicationContext(),
									CapituloI_Activity.class);
							Bundle b = getIntent().getExtras();
							b.putString(var.ID_LOCAL, id_local);
							b.putInt(var.NRO_PRED, Nro_Pred);
							b.putInt("rural", rural);
							irEnvio.putExtras(b);
							startActivity(irEnvio);
							dialog.cancel();
							finish();
						} else if (which == 3) {
							Intent irEnvio = new Intent(
									getApplicationContext(),
									Envio_Datos_Activity.class);
							Bundle b = getIntent().getExtras();
							b.putString(var.ID_LOCAL, id_local);
							b.putString(var.CODIGO_PATRIMONIAL,
									b.getString(var.CODIGO_PATRIMONIAL));
							irEnvio.putExtras(b);
							startActivity(irEnvio);
							dialog.cancel();
							finish();
						} else if (which == 1) {
							CrearConfirmacion(id_local);

						}
					}
				});

		AlertDialog dialogo = builder.create();
		dialogo.show();
	}

	public void CrearConfirmacion(final String id_local) {
		dialogoE = new Dialog(this);
		dialogoE.setTitle("Confirmar exportaci\u00f3n");
		dialogoE.setCancelable(false);
		dialogoE.setContentView(R.layout.confirmacion_envio);
		etClave = (EditText) dialogoE.findViewById(R.id.etClave);
		Button bAceptar = (Button) dialogoE.findViewById(R.id.bAceptar);
		bAceptar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (etClave.getText().toString().length() == 0) {
					Toast.makeText(Carga_Trabajo_Activity.this,
							"Ingrese la clave de seguridad", Toast.LENGTH_SHORT)
							.show();
				} else if (!principal.ConfirmarClave2(etClave.getText()
						.toString())) {
					Toast.makeText(Carga_Trabajo_Activity.this,
							"La clave ingresada es incorrecta",
							Toast.LENGTH_SHORT).show();
				} else {
					try {
						File sdCard = Environment.getExternalStorageDirectory();
						File directory = new File(sdCard.getAbsolutePath()
								+ "/SQLCIE2013/" + id_local);
						directory.mkdirs();
						File file = new File(directory, id_local + ".xml");
						FileOutputStream fout = new FileOutputStream(file);
						PrincipalDao principal = new PrincipalDao(
								getApplicationContext());
						OutputStreamWriter ows = new OutputStreamWriter(fout);

						String script = "";

						// CARATULA
						List<Object> lista0 = principal.sql0(id_local);

						List<String> script0 = (List<String>) lista0.get(0);
						if (script0 != null) {
							for (String sql0 : script0) {
								script += sql0 + "\n";
							}
						}

						List<String> script0c = (List<String>) lista0.get(1);
						if (script0c != null) {
							for (String sql0c : script0c) {
								script += sql0c + "\n";
							}
						}
						// CARATULA

						// 1
						List<Object> lista1 = principal.sql1(id_local);

						List<String> script1a28 = (List<String>) lista1.get(0);
						if (script1a28 != null) {
							for (String sql1 : script1a28) {
								script += sql1 + "\n";
							}
						}

						List<String> script1a29 = (List<String>) lista1.get(1);
						if (script1a29 != null) {
							for (String sql1 : script1a29) {
								script += sql1 + "\n";
							}
						}

						List<String> script1a2n = (List<String>) lista1.get(2);
						if (script1a2n != null) {
							for (String sql1 : script1a2n) {
								script += sql1 + "\n";
							}
						}

						List<String> script1a = (List<String>) lista1.get(3);
						if (script1a != null) {
							for (String sql1 : script1a) {
								script += sql1 + "\n";
							}
						}

						List<String> script1b2a = (List<String>) lista1.get(4);
						if (script1b2a != null) {
							for (String sql1 : script1b2a) {
								script += sql1 + "\n";
							}
						}

						List<String> script1b312n = (List<String>) lista1
								.get(5);
						if (script1b312n != null) {
							for (String sql1 : script1b312n) {
								script += sql1 + "\n";
							}
						}

						List<String> script1b3n = (List<String>) lista1.get(6);
						if (script1b3n != null) {
							for (String sql1 : script1b3n) {
								script += sql1 + "\n";
							}
						}

						List<String> script1b = (List<String>) lista1.get(7);
						if (script1b != null) {
							for (String sql1 : script1b) {
								script += sql1 + "\n";
							}
						}

						List<String> script1c20n = (List<String>) lista1.get(8);
						if (script1c20n != null) {
							for (String sql1 : script1c20n) {
								script += sql1 + "\n";
							}
						}

						List<String> script1c = (List<String>) lista1.get(9);
						if (script1c != null) {
							for (String sql1 : script1c) {
								script += sql1 + "\n";
							}
						}

						// 2
						List<Object> lista2 = principal.sql2(id_local);

						List<String> script2a = (List<String>) lista2.get(0);
						if (script2a != null) {
							for (String sql2 : script2a) {
								script += sql2 + "\n";
							}
						}

						List<String> script2b10 = (List<String>) lista2.get(1);
						if (script2b10 != null) {
							for (String sql2 : script2b10) {
								script += sql2 + "\n";
							}
						}

						List<String> script2b11 = (List<String>) lista2.get(2);
						if (script2b11 != null) {
							for (String sql2 : script2b11) {
								script += sql2 + "\n";
							}
						}

						List<String> script2b12n = (List<String>) lista2.get(3);
						if (script2b12n != null) {
							for (String sql2 : script2b12n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2b9n = (List<String>) lista2.get(4);
						if (script2b9n != null) {
							for (String sql2 : script2b9n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2b = (List<String>) lista2.get(5);
						if (script2b != null) {
							for (String sql2 : script2b) {
								script += sql2 + "\n";
							}
						}

						List<String> script2c = (List<String>) lista2.get(6);
						if (script2c != null) {
							for (String sql2 : script2c) {
								script += sql2 + "\n";
							}
						}

						List<String> script2d1n = (List<String>) lista2.get(7);
						if (script2d1n != null) {
							for (String sql2 : script2d1n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2d3n = (List<String>) lista2.get(8);
						if (script2d3n != null) {
							for (String sql2 : script2d3n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2d5n = (List<String>) lista2.get(9);
						if (script2d5n != null) {
							for (String sql2 : script2d5n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2d7n = (List<String>) lista2.get(10);
						if (script2d7n != null) {
							for (String sql2 : script2d7n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2d9n = (List<String>) lista2.get(11);
						if (script2d9n != null) {
							for (String sql2 : script2d9n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2d = (List<String>) lista2.get(12);
						if (script2d != null) {
							for (String sql2 : script2d) {
								script += sql2 + "\n";
							}
						}

						List<String> script2e = (List<String>) lista2.get(13);
						if (script2e != null) {
							for (String sql2 : script2e) {
								script += sql2 + "\n";
							}
						}

						List<String> script2f = (List<String>) lista2.get(14);
						if (script2f != null) {
							for (String sql2 : script2f) {
								script += sql2 + "\n";
							}
						}

						List<String> script2g2n = (List<String>) lista2.get(15);
						if (script2g2n != null) {
							for (String sql2 : script2g2n) {
								script += sql2 + "\n";
							}
						}

						List<String> script2g = (List<String>) lista2.get(16);
						if (script2g != null) {
							for (String sql2 : script2g) {
								script += sql2 + "\n";
							}
						}

						// 2

						// 3
						List<Object> lista3 = principal.sql3(id_local);
						List<String> scripts = (List<String>) lista3.get(0);

						if (scripts != null) {
							for (String sql3 : scripts) {
								script += sql3 + "\n";
							}
						}
						List<String> scriptsGPS = (List<String>) lista3.get(1);
						if (scriptsGPS != null) {
							for (String sqlGPS : scriptsGPS) {
								script += sqlGPS + "\n";
							}
						}
						// 3

						// 4
						List<Object> lista4 = principal.sql4(id_local);

						List<String> script4 = (List<String>) lista4.get(0);
						if (script4 != null) {
							for (String sql4 : script4) {
								script += sql4 + "\n";
							}
						}

						List<String> script42n = (List<String>) lista4.get(1);
						if (script42n != null) {
							for (String sql42n : script42n) {
								script += sql42n + "\n";
							}
						}
						// 4

						// 5
						List<Object> lista5 = principal.sql5(id_local);

						List<String> script5f = (List<String>) lista5.get(0);
						if (script5f != null) {
							for (String sql5f : script5f) {
								script += sql5f + "\n";
							}
						}

						List<String> script5n = (List<String>) lista5.get(1);
						if (script5n != null) {
							for (String sql5n : script5n) {
								script += sql5n + "\n";
							}
						}

						List<String> script5 = (List<String>) lista5.get(2);
						if (script5 != null) {
							for (String sql5 : script5) {
								script += sql5 + "\n";
							}
						}
						// 5

						// 6
						List<Object> lista6 = principal.sql6(id_local);

						List<String> script6110n = (List<String>) lista6.get(0);
						if (script6110n != null) {
							for (String sql6110n : script6110n) {
								script += sql6110n + "\n";
							}
						}

						List<String> script618n = (List<String>) lista6.get(1);
						if (script618n != null) {
							for (String sql618n : script618n) {
								script += sql618n + "\n";
							}
						}

						List<String> script61 = (List<String>) lista6.get(2);
						if (script61 != null) {
							for (String sql61 : script61) {
								script += sql61 + "\n";
							}
						}

						List<String> script624n = (List<String>) lista6.get(3);
						if (script624n != null) {
							for (String sql624n : script624n) {
								script += sql624n + "\n";
							}
						}

						List<String> script62 = (List<String>) lista6.get(4);
						if (script62 != null) {
							for (String sql62 : script62) {
								script += sql62 + "\n";
							}
						}
						// 6

						// 7
						List<Object> lista7 = principal.sql7(id_local);

						List<String> script7 = (List<String>) lista7.get(0);
						if (script7 != null) {
							for (String sql7 : script7) {
								script += sql7 + "\n";
							}
						}
						// 7

						// 8
						List<Object> lista8 = principal.sql8(id_local);

						List<String> script8 = (List<String>) lista8.get(0);
						if (script8 != null) {
							for (String sql8 : script8) {
								script += sql8 + "\n";
							}
						}
						// 8

						// 9

						List<Object> lista9 = principal.sql9(id_local);

						List<String> script9 = (List<String>) lista9.get(0);
						if (script9 != null) {
							for (String sql9 : script9) {
								script += sql9 + "\n";
							}
						}

						// 9
						
						String scriptFinal = "";
						
						scriptFinal = script.replace("'null'","NULL");
						
						ows.write(scriptFinal);
						ows.flush();
						ows.close();

						Toast.makeText(Carga_Trabajo_Activity.this,
								"Exportado con exito", Toast.LENGTH_SHORT)
								.show();
						dialogoE.cancel();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
		Button bCancelar = (Button) dialogoE.findViewById(R.id.bCancelar);
		bCancelar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				dialogoE.cancel();
			}
		});
		dialogoE.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.menu_carga_trabajo, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnSalir:
			AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
			dialogo1.setTitle("Importante");
			dialogo1.setMessage("Deseas Salir ?");
			dialogo1.setIcon(android.R.drawable.ic_dialog_alert);
			dialogo1.setCancelable(false);
			dialogo1.setPositiveButton("Si",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialogo1, int id) {
							System.exit(0);
						}
					});

			dialogo1.setNegativeButton("No",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialogo1, int id) {
							return;
						}
					});
			dialogo1.show();
			break;
		case R.id.mnMensajeria:
			Intent irMensajeria = new Intent(this, Mensajeria_Activity.class);
			irMensajeria.putExtras(getIntent().getExtras());
			startActivity(irMensajeria);
			finish();
			break;
		case R.id.mnBPR:
			Intent irBPR = new Intent(this, BPR_Activity.class);
			irBPR.putExtras(getIntent().getExtras());
			startActivity(irBPR);
			finish();
			break;
		case R.id.mnMarco:
			progreso = new ProgressDialog(this);
			progreso.setTitle("Cargando...");
			progreso.setMessage("Actualizando marco");
			progreso.setProgress(0);
			progreso.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progreso.setMax(100);
			progreso.show();
			Cargar cargar = new Cargar();
			cargar.execute();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public class Cargar extends AsyncTask<Void, Integer, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				for (int i = 0; i < 100; i++) {
					Thread.sleep(100);
					publishProgress(i);
				}
			} catch (Exception e) {

			}
			progreso.dismiss();
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			progreso.setProgress(values[0]);
		}

	}

}
